package com.ww.springboot.boot.thread.study.base.lock.aqs.demo.lock2;

import com.ww.springboot.boot.thread.study.base.lock.aqs.util.ThreadPrintUtil;

/**
 * 描述：
 *
 * @author 🧑 ‍wanwei
 * @since 2023-03-17 09:52
 */
public class LockDemo2 {

    public static void main(String[] args) {
        //测试重入锁是否可实现多个线程排队获取锁
        MySimpleReentrantLock mySimpleReentrantLock = new MySimpleReentrantLock();

        Thread thread = new Thread(() -> {
            ThreadPrintUtil.sout("开始");
            mySimpleReentrantLock.lock();
            try {
                for (int i = 0; i < 5; i++) {
                    mySimpleReentrantLock.lock();
                    ThreadPrintUtil.sout("获取锁" + i);
                    Thread.sleep(1000);
                    mySimpleReentrantLock.unlock();
                    ThreadPrintUtil.sout("解锁" + i);
                }
            } catch (Exception e) {

            } finally {
                ThreadPrintUtil.sout("解锁");
                mySimpleReentrantLock.unlock();
            }
        });

        Thread thread2 = new Thread(() -> {
            ThreadPrintUtil.sout("开始");
            mySimpleReentrantLock.lock();
            try {
                for (int i = 0; i < 5; i++) {
                    mySimpleReentrantLock.lock();
                    ThreadPrintUtil.sout("获取锁" + i);
                    Thread.sleep(2000);
                    mySimpleReentrantLock.unlock();
                    ThreadPrintUtil.sout("解锁" + i);
                }
            } catch (Exception e) {

            } finally {
                ThreadPrintUtil.sout("解锁");
                mySimpleReentrantLock.unlock();
            }
        });

        thread.start();
        thread2.start();
    }
}
